//
//  NearbyShopsVC.swift
//  XiaoJingMallSwift
//
//  Created by beisheng03 on 2017/8/4.
//  Copyright © 2017年 beisheng. All rights reserved.
//

import UIKit
import DOPDropDownMenu_Enhanced
import SVProgressHUD
struct  Location{
    
    var latitude : String
    
    var longitude : String
    
    init(lat : String,long: String) {
        
        self.latitude = lat
        
        self.longitude = long
    }
}

struct Parameter {
    var keyword : String?
    var order_type : String?
    var sc_id : String?
    var districtId : String?
    
    init(keyword : String?,order_type: String?,sc_id: String?,districtId: String?) {
        
        self.keyword = keyword
        
        self.order_type = order_type
        
        self.sc_id = sc_id
        
        self.districtId = districtId
    }
    
    
}

class NearbyShopsVC: BaseViewController {
    
    var location : Location!
    
    var requestParameter = Parameter(keyword: nil, order_type: nil, sc_id: nil, districtId: nil)
    
    var page = -999

    var dataModel : NearbyShopsModel?
    
    var citysData : [ProvinceModel]?
    
    
    var industryModel : SelectIndustryModel?
    
    var distanceModel : SelectDistanceModel?
    

    
    lazy var menuView : DOPDropDownMenu = {
    
       let temp = DOPDropDownMenu(origin: CGPoint(x: 0, y: 64), andHeight: 44)
        
        temp!.delegate = self
        
        temp!.dataSource = self
        
    
    return temp!
        
    }()

    override func viewDidLoad() {
        super.viewDidLoad()
        
        setNav()
        
        loadCitysInfoAndSelectCondition()
        
        groupTableView.rowHeight = 106
        
        groupTableView.contentInset = UIEdgeInsetsMake(44, 0, 0, 0)
        
        groupTableView.register(UINib(nibName: StringFromClass(classType: NearbyShopsCell.self), bundle: nil), forCellReuseIdentifier: NearbyShopsCell.identifer())
        
        
        weak var weakSelf = self
        
        groupTableView.mj_header =  ZMRefreshHeader.init {
            
            weakSelf!.loadData()
            
        }
        
        groupTableView.mj_header.beginRefreshing()
        
         groupTableView.mj_footer = ZMRefreshFooter.init{
            
            weakSelf!.loadMoreData()
            
        }


    }
    
    
    
    func setNav() {
        
        
        navigationItem.leftBarButtonItem = UIBarButtonItem(barButtonSystemItem: .reply, target: self, action: #selector(backBtnDidTap))
        
        let bgView = NavTittleView(frame: CGRect(x: 0, y: 0, width: KScreenW, height: 44))
        
        bgView.backgroundColor = UIColor.clear
        
        let leftBtn = LightDisableBtn(type: .custom)
        
        leftBtn.frame = CGRect(x: 0, y: 0, width: 50, height: 44)
        
        leftBtn.backgroundColor = UIColor.clear
        
        leftBtn.addTarget(self, action: #selector(backBtnDidTap), for: .touchUpInside)
        
//        leftBtn.backgroundColor = UIColor.red
        
        bgView.addSubview(leftBtn)
        
        let btn = LightDisableBtn(type: .custom)
        
        btn.frame = CGRect(x: 50, y: 6, width: KScreenW - 70, height: 32)
        
        btn.setBackgroundImage(UIImage(named: "bg_search_bar_7_gray"), for: .normal)
        
        btn.addTarget(self, action: #selector(tittleBtnDidTap), for: .touchUpInside)
        
        btn.backgroundColor = UIColor.clear
        
        bgView.addSubview(btn)
        
        let label = UILabel()
        
        label.text = "店铺搜索"
        
        label.font = UIFont.systemFont(ofSize: 14)
        
        label.textColor = UIColor.colorWith(r: 145, g: 145, b: 145)
        
        label.sizeToFit()
        
        label.frame = CGRect(x: 30, y: 0, width: label.frame.size.width, height: 32)
        
        label.isUserInteractionEnabled = false
        
        btn.addSubview(label)
        
        navigationItem.titleView = bgView
        
        
    }
    
    
    func backBtnDidTap(){
        
        navigationController?.popViewController(animated: true)
        
    }
    
    
    func tittleBtnDidTap(){
        
        let tmepV = SearchController()
        
        
        let nav = BaseNavController(rootViewController: tmepV)
        
        
        present(nav, animated: true, completion: nil)
        
    }
    

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    

  
}



extension NearbyShopsVC{
    
    
    func loadCitysInfoAndSelectCondition(){
        
        
        let grop = DispatchGroup()
        
        grop.enter()


        NetworkTools.shared.sendRequest(method: .GET_METHOD, pathStr: "mobile/index.php?c=index&a=get_area_list", parameters: nil) {[weak self] (responseObject, error) in
            
            if error == nil{
                
                self!.citysData = [ProvinceModel]()
                
                for dic in responseObject!["datas"]!["area_list"] as! [[String : AnyObject]]{
                    
                    
                    self!.citysData!.append(ProvinceModel(dic: dic))
                    
                    
                }
                
                
                let last = CityModel(dic: ["city_name" : "全部区域" as AnyObject,"city_id" : "0" as AnyObject])
                
                let temp = ProvinceModel()
                
                temp.province_name = "区域"
                
                temp.citys = [last]
                
                self!.citysData!.insert(temp, at: 0)
                
                
                grop.leave()
                
                
                
            }else{
                
                
                SVProgressHUD.showError(withStatus: error?.domain)
                
                
            }
        }
        
        
        
        
        
        
        
        
        
        
        
        grop.enter()

        NetworkTools.shared.sendRequest(method: .GET_METHOD, pathStr: "mobile/index.php?c=merchant&a=filter_options", parameters: nil) { [weak self] (responseObject, error) in
            
            if error == nil {
            
                guard let temp = responseObject?["datas"]?["filter"] as? [[String : AnyObject]] else{
                    
                    
                    return
                    
                }
                
                
             self!.industryModel = SelectIndustryModel(dic: temp[0])
                
             self!.distanceModel = SelectDistanceModel(dic: temp[1])
            

                grop.leave()

            }else{
            
                SVProgressHUD.showError(withStatus: error?.domain)

            
            }
            
            
        }
        
        
        
        grop.notify(queue: DispatchQueue.main) {
        

            self.creatDropDownMenu()

        }
        
        
    
    }
    
    
    
    func creatDropDownMenu()  {
        
        view.addSubview(menuView)
        


    }
    
    
    
    
    
    
    


    func loadData() {
        
        page = 1
        
        var tempParmeter  = [String : AnyObject]()
        
        tempParmeter["curpage"] = "\(page)" as AnyObject
        
        tempParmeter["lat"] = location.latitude as AnyObject;
        
        tempParmeter["lng"] = location.longitude as AnyObject;
        
        if requestParameter.keyword != nil {
            
            tempParmeter["keyword"] = requestParameter.keyword! as AnyObject
            
        }
        
        if requestParameter.order_type != nil {
            
            
            tempParmeter["order_type"] = requestParameter.order_type! as AnyObject
            
        }
        
        if requestParameter.sc_id != nil {
            
            tempParmeter["sc_id"] = requestParameter.sc_id! as AnyObject
            
        }
        
        
        if requestParameter.districtId != nil {
            
            tempParmeter["district_id"] = requestParameter.districtId! as AnyObject
            
        }
        

        
        
        NetworkTools.shared.sendRequest(method: .GET_METHOD, pathStr: "mobile/index.php?c=merchant&a=get_list", parameters: tempParmeter) {[weak self] (responseObject, error) in
            
            if error == nil {
                
                self!.dataModel = NearbyShopsModel(dic: responseObject!)
                
                self!.dataModel!.listModels = [ShopInfoModel]()
                
                
                for dic in responseObject!["datas"]!["list"] as! [[String : AnyObject]]{
                    
                    self!.dataModel!.listModels!.append(ShopInfoModel(dic: dic))
                    
                }
                
                
                
                self!.groupTableView.mj_footer.resetNoMoreData()
                
                self!.groupTableView.mj_footer.resetNoMoreData()
                
                if self!.dataModel!.hasmore == "0" {
                    
                    self!.groupTableView.mj_footer.endRefreshingWithNoMoreData()
                    
                    
                }
                
                
                if self!.dataModel!.listModels!.count == 0{
                    
                    self!.showLogoView(text : "暂无商铺数据...")
                    
                    self!.groupTableView.mj_header.endRefreshing()
                    
                    self!.groupTableView.reloadData()
                    
                    return
                }else{
                    
                    self!.dissmissLogoView()
                }
                
                
                
                self!.groupTableView.mj_header.endRefreshing()
                
                self!.groupTableView.reloadData()
                
                self!.groupTableView.scrollToRow(at: IndexPath(row: 0, section: 0), at: .top, animated: true)
                
            }else{
                
                self!.groupTableView.mj_header.endRefreshing()
                
                SVProgressHUD.showError(withStatus: error?.domain)
                
                
            }
            
            
        }




}
    
    
    
    
    
    
    func loadMoreData() {
        
        page += 1

        var tempParmeter  = [String : AnyObject]()
        
        tempParmeter["curpage"] = "\(page)" as AnyObject
        
        tempParmeter["lat"] = location.latitude as AnyObject
        
        tempParmeter["lng"] = location.longitude as AnyObject
        
        if requestParameter.keyword != nil {
            
            tempParmeter["keyword"] = requestParameter.keyword! as AnyObject
            
        }
        
        if requestParameter.order_type != nil {
            
            tempParmeter["order_type"] = requestParameter.order_type! as AnyObject
            
        }
        
        if requestParameter.sc_id != nil {
            
            tempParmeter["sc_id"] = requestParameter.sc_id! as AnyObject
            
        }
        
        
        if requestParameter.keyword != nil {
            
            tempParmeter["districtId"] = requestParameter.districtId! as AnyObject
            
        }
        
        
        
        
        
        
        NetworkTools.shared.sendRequest(method: .GET_METHOD, pathStr: "mobile/index.php?c=merchant&a=get_list", parameters: tempParmeter) {[weak self] (responseObject, error) in
            
            if error == nil {
                
                let temp = self!.dataModel!.listModels
                
                self!.dataModel = NearbyShopsModel(dic: responseObject!)
                
                self!.dataModel!.listModels = temp
                
                
                for dic in responseObject!["datas"]!["list"] as! [[String : AnyObject]]{
                    
                    self!.dataModel!.listModels!.append(ShopInfoModel(dic: dic))
                    
                }
                
                
                
                if self!.dataModel!.hasmore == "0" {
                    
                    self!.groupTableView.mj_footer.endRefreshingWithNoMoreData()
                    
                }else{
                
                    self!.groupTableView.mj_footer.endRefreshing()
                
                }
                
                 
                
                self!.groupTableView.reloadData()
                
            }else{
                
                self!.groupTableView.mj_footer.endRefreshing()
                
                SVProgressHUD.showError(withStatus: error?.domain)
                
                
            }
            
            
        }

        
        
    }

}


extension NearbyShopsVC{


    override func numberOfSections(in tableView: UITableView) -> Int {
        
        
        if dataModel == nil {
            return 0
        }
        
        if dataModel!.listModels!.count > 0 {
            
            return 1
            
        } else {
            
            return 0
            
        }
        
        
    }
    
    
    
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

        if dataModel == nil {
            return 0
        }
        

        return dataModel?.listModels?.count ?? 0
        
    }
    
    
    
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        

        let tableCell : NearbyShopsCell =  tableView.dequeueReusableCell(withIdentifier: NearbyShopsCell.identifer()) as! NearbyShopsCell
        

        
        tableCell.model = dataModel?.listModels?[indexPath.row]

        
        
        return tableCell
        
    }
    
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {

        return 106
    }
    
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {

        return 0.00001
    }
    
    
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {

        return 0.00001
        
    }
    
    
    
    
    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        //        super.tableView(tableView, didSelectRowAt: indexPath)
        
        let temp = ShopsDetailController()
        
        temp.merchantId = dataModel?.listModels?[indexPath.row].merchant_id ?? "-999"
        
        
        navigationController?.pushViewController(temp, animated: true)
        
    }
    
    




}




extension NearbyShopsVC : DOPDropDownMenuDelegate,DOPDropDownMenuDataSource{

    
    func menu(_ menu: DOPDropDownMenu!, didSelectRowAt indexPath: DOPIndexPath!) {
//        
//        QL1(indexPath.column)
//        QL1(indexPath.row)
        QL1(indexPath.item)
//        return
        switch indexPath.column {
        case 0:
            
            if indexPath.item > -1 {
                requestParameter.keyword = nil
                requestParameter.order_type = nil
                requestParameter.sc_id = nil
                requestParameter.districtId = citysData![indexPath.row].citys[indexPath.item].city_id
                dataModel = nil
                loadData()
              }
            
        case 1:
            
            requestParameter.keyword = nil
            requestParameter.order_type = nil
            requestParameter.sc_id = industryModel?.options[indexPath.row].sc_id
            requestParameter.districtId = nil
            dataModel = nil
            loadData()

        default:
            
            requestParameter.keyword = nil
            requestParameter.order_type = distanceModel?.options[indexPath.row].order_type
            requestParameter.sc_id = nil
            requestParameter.districtId = nil
            dataModel = nil
            loadData()

        }
        


    }

    
    func numberOfColumns(in menu: DOPDropDownMenu!) -> Int{
    
      return 3
        
    }

    
    func menu(_ menu: DOPDropDownMenu!, numberOfRowsInColumn column: Int) -> Int {
        switch column {
        case 0:
            
            return citysData!.count

          case 1:
            return industryModel?.options.count ?? 0

            case 2:
                return distanceModel?.options.count ?? 0

        default:
            return 0
 
        }
        
        
    }
    
    
    func menu(_ menu: DOPDropDownMenu!, numberOfItemsInRow row: Int, column: Int) -> Int {
        
        switch column {
        case 0:
            
            return citysData![row].citys.count
            
        default:
            return 0
        }
        
    }
    
    
    func menu(_ menu: DOPDropDownMenu!, titleForRowAt indexPath: DOPIndexPath!) -> String! {
        
        switch indexPath.column {
            
        case 0:
            
            return citysData![indexPath.row].province_name
        case 1:
            
            return industryModel?.options[indexPath.row].sc_name
            
        default:
            
            return distanceModel?.options[indexPath.row].text
            
            
        }

        

    }
    
    
    
    
    func menu(_ menu: DOPDropDownMenu!, titleForItemsInRowAt indexPath: DOPIndexPath!) -> String! {
        
        
        switch indexPath.column {
            
        case 0:
            
            return citysData![indexPath.row].citys[indexPath.item].city_name
            
        default:
            
            return ""
            
            
        }
    }
    
    
    
}
